package com.free.food.product.service.impl;

import com.free.food.core.enums.ResultEnum;
import com.free.food.core.enums.product.ProductStatusEnum;
import com.free.food.core.exception.ProductException;
import com.free.food.core.util.DateUtil;
import com.free.food.product.dto.CartDTO;
import com.free.food.product.entity.ProductInfo;
import com.free.food.product.repository.ProductInfoRepository;
import com.free.food.product.req.DecreaseStockReq;
import com.free.food.product.res.FindProductInfoRes;
import com.free.food.product.service.ProductService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * 类功能描述：
 *
 * @author：刘富国
 * @createTime：2019-02-08 11:40
 */
@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductInfoRepository productInfoRepository;

    @Override
    public List<FindProductInfoRes> findUpAll() {
        List<FindProductInfoRes> res = new ArrayList<>();
        List<ProductInfo> productInfoList = productInfoRepository.findByProductStatus(ProductStatusEnum.UP.getCode());
        for (ProductInfo productInfo : productInfoList) {
            FindProductInfoRes productInfoRes = new FindProductInfoRes();
            BeanUtils.copyProperties(productInfo, productInfoRes);
            res.add(productInfoRes);
        }
        return res;
    }

    @Override
    public List<FindProductInfoRes> findByProductIdIn(List<String> productIdList) {
        List<FindProductInfoRes> res = new ArrayList<>();
        List<ProductInfo> productInfoList = productInfoRepository.findByProductIdIn(productIdList);
        for (ProductInfo productInfo : productInfoList) {
            FindProductInfoRes productInfoRes = new FindProductInfoRes();
            BeanUtils.copyProperties(productInfo, productInfoRes);
            res.add(productInfoRes);
        }
        return res;
    }


    @Override
    public void decreaseStock(List<DecreaseStockReq> cartDTOList) {
        for (DecreaseStockReq cartDTO : cartDTOList) {
            Optional<ProductInfo> productInfoOptional = productInfoRepository.findById(cartDTO.getProductId());
            if (!productInfoOptional.isPresent()) {
                throw new ProductException(ResultEnum.PRODUCT_NOT_EXIST);
            }
            ProductInfo productInfo = productInfoOptional.get();
            int num = productInfo.getProductStock() - cartDTO.getProductQuantity();
            if (num < 0) {
                throw new ProductException(ResultEnum.PRODUCT_NUM_ERROR);
            }
            productInfo.setProductStock(num);
            productInfo.setUpdateTime(DateUtil.getCurrentTimeStamp());
            productInfoRepository.save(productInfo);

        }
    }
}
